/*
 * @Description:
 * @Autor: GuluGuluu
 * @Date: 2023-06-24 14:24:54
 * @LastEditors: GuluGuluu
 * @LastEditTime: 2023-06-26 14:18:44
 */
import React, { useState } from "react";
import UserService, { TOKEN_KEY } from "../service/user.service";
import { useMount } from "../utils";

const bootstrapUser = async () => {
  let user = null;

  return user;
};
const AuthContext = React.createContext(undefined);
AuthContext.displayName = "AuthContext";

export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null); // 这里需要使用泛型

  const login = (form) => UserService.login(form).then(setUser);
  const register = (form) => UserService.register(form).then(setUser);
  const logout = () => {
    UserService.logout();
    setUser(null);
  };

  // 挂载时，获取用户信息
  useMount(() => {
    bootstrapUser().then(setUser);
  });

  return (
    <AuthContext.Provider
      children={children}
      value={{ user, login, register, logout }}
    />
  );
};

export const useAuth = () => {
  const context = React.useContext(AuthContext);
  if (!context) {
    throw new Error("useAuth必须在AuthProvider中使用");
  }
  return context;
};
